<script setup lang='ts'>
import { ref, onMounted, onUnmounted, reactive, watch } from 'vue'
import * as echarts from 'echarts'
import { useHotSaleStore } from '@/store/saleInfoStore/useHotSaleStore'
import { storeToRefs } from 'pinia'

const hotSaleStore = useHotSaleStore()
// 获取仓库书籍销量数据
const {saleData} = storeToRefs(hotSaleStore)

const chartDom = ref(null)
let myChart:echarts.ECharts| null=null
const data = reactive({
    // 使用仓库数据
    saleData
})

// 监测数据，更新图表
watch(data,()=>{
    if(myChart){
        myChart.setOption({
            series: [
                {
                  name:data.saleData[0].name,
                  data: data.saleData[0].value,
                  type: 'line'
                },
                {
                  name:data.saleData[1].name,
                  data:data.saleData[1].value,
                  type:'line'
                },
                {
                  name:data.saleData[2].name,
                  data:data.saleData[2].value,
                  type:'line'
                },
                {
                  name:data.saleData[3].name,
                  data:data.saleData[3].value,
                  type:'line'
                },
                {
                  name:data.saleData[4].name,
                  data:data.saleData[4].value,
                  type:'line'
                }
            ]         
        })
    }
})

// 配置项
const option:echarts.EChartsOption = {
  tooltip:{
    trigger:'axis'
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月','8月','9月','10月','11月','12月']
  },
  yAxis: {
    type: 'value',
    min:0,
    max:2000
  },
  series: [
    {
      name:data.saleData[0].name,
      data: data.saleData[0].value,
      type: 'line'
    },
    {
      name:data.saleData[1].name,
      data:data.saleData[1].value,
      type:'line'
    },
    {
      name:data.saleData[2].name,
      data:data.saleData[2].value,
      type:'line'
    },
    {
      name:data.saleData[3].name,
      data:data.saleData[3].value,
      type:'line'
    },
    {
      name:data.saleData[4].name,
      data:data.saleData[4].value,
      type:'line'
    }
  ]
}

// 挂载时初始化图表
onMounted(()=>{
    if(chartDom.value){
        myChart = echarts.init(chartDom.value)
        myChart.setOption(option)
    }
})

// 卸载组件时销毁
onUnmounted(()=>{
    myChart?.dispose()
})

</script>

<template>
    <div ref="chartDom" style="width: 100%; height: 400px; background-color: #fff;"></div>
</template>

<style scoped>
</style>